package DBTasks;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 
 * @author Stephen
 * 
 */

public class AddPet extends DBTask {

    private static String addPetSQL = "INSERT INTO Pet (Shelter_Name, Age, Gender, Pet_Name) "
            + "values (?, ?, ? ,?)";

    private static String addDogSQL = "INSERT INTO Dog (Pet_ID, Shelter_Name, Breed) values (?, ?, ?)";

    private static String addCatSQL = "INSERT INTO Cat (Pet_ID, Shelter_Name, Breed) values(?, ?, ?)";

    public static boolean addPet(String shelterName, boolean dog, String breed,
            String gender, String petName, String age) {

        boolean success = false;

        try {

            // add the Pet to the pet db
            PreparedStatement addPetQuery = con.prepareStatement(addPetSQL,
                    Statement.RETURN_GENERATED_KEYS);

            addPetQuery.setString(1, shelterName);
            addPetQuery.setString(2, age);
            addPetQuery.setString(3, new String(gender));
            addPetQuery.setString(4, petName);

            addPetQuery.execute();

            // now add it to the dog or cat depending on which it is
            ResultSet keys = addPetQuery.getGeneratedKeys();
            keys.first();
            int petID = keys.getInt(1);

            String addTypeSQL = addDogSQL;
            if (!dog) {
                addTypeSQL = addCatSQL;
            }

            PreparedStatement addType = con.prepareStatement(addTypeSQL);
            addType.setInt(1, petID);
            addType.setString(2, shelterName);
            addType.setString(3, breed);

            addType.execute();
            success = true;

        }
        catch (SQLException e) {
            e.printStackTrace();
            success = false;
        }

        return success;
    }
}
